package com.example.receiptocr.viewModels

import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.receiptocr.api.ReceiptApi
import com.example.receiptocr.bodys.requestBodys.ReceiptResultBody
import com.example.receiptocr.bodys.responseBodys.BackReceipt
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
import java.math.BigDecimal
import java.time.LocalDate

// 重命名为OCRResultState以避免冲突
sealed class OCRResultState {
    object Loading : OCRResultState()
    data class Success(val backReceipt: BackReceipt) : OCRResultState()
    data class Error(val message: String) : OCRResultState()
}

@HiltViewModel
class OCRResultViewModel @Inject constructor(
    private val api: ReceiptApi
) : ViewModel() {
    
    private val _resultState = MutableStateFlow<OCRResultState>(OCRResultState.Loading)
    val resultState: StateFlow<OCRResultState> = _resultState
    
    fun ocrReceipt(uri: Uri) {
        viewModelScope.launch {
            _resultState.value = OCRResultState.Loading
            try {
                val response = BackReceipt (
                    receiptName = "suhuanzhen",
                    receiptCode = 0,
                    receiptNumber = 0,
                    receiptDate = LocalDate.now(),
                    purchaserName = "",
                    purchaserCode = "",
                    purchaserAddress = "",
                    purchaserBank = "",
                    sellerName = "",
                    sellerCode = "",
                    sellerAddress = "",
                    sellerBank = "",
                    totalAmount = 0.0,
                    note = ""
                )
                _resultState.value = OCRResultState.Success(response)
            } catch (e: Exception) {
                _resultState.value = OCRResultState.Error(e.message ?: "加载失败")
            }
        }
    }
    
    fun saveReceipt(backReceipt: BackReceipt) {
        viewModelScope.launch {
            try {
                val response = api.addReceipt(backReceipt)
                if (!response.isSuccessful) {
                    _resultState.value = OCRResultState.Error("保存失败：${response.message()}")
                }
            } catch (e: Exception) {
                _resultState.value = OCRResultState.Error(e.message ?: "保存失败")
            }
        }
    }
}

